#include "FolderInotify.h"

#include<stdio.h>
#include<assert.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<sys/inotify.h>
#include<limits.h>
#include<fcntl.h>

#define BUF_LEN 1000

FolderInotify::FolderInotify()
{
    inotifyEventDeal = NULL;
    exitflag = false;
    dealParam = NULL;
    mask = 0;
}


FolderInotify::~FolderInotify()
{
    
}


bool FolderInotify::init()
{
    inotifyFd = inotify_init();
    if(inotifyFd == -1)  
    {
        perror("inotify_init Err:");
    }
}

bool FolderInotify::inotifyAddWatch(char * folderName)
{
    wd = inotify_add_watch(inotifyFd, folderName, mask);
    if(wd == -1)
    {
        perror("inotify_add_watch Err:\n");
    }
}

void FolderInotify::run()
{
    char buf[BUF_LEN];
    ssize_t numRead;
    char *p;
    struct inotify_event *event;
    int flags;
    
    while(!exitflag)
    {
        numRead = read(inotifyFd,buf,BUF_LEN);
        if(numRead == -1)
        {
            perror("read Err:\n");
        }

        for( p=buf; p < buf+numRead; )
        {
            event = (struct inotify_event *)p;
            inotifyEventDeal(dealParam, event);
            p+=sizeof(struct inotify_event) + event->len;
        }
    }
}


void FolderInotify::stop()
{
    exitflag = true; 
}


void FolderInotify::start()
{
    exitflag = false; 
}